package com.hongsuan.pplive.mobileAPI.sys;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.cnjson.common.config.Global;
import com.cnjson.common.utils.DateUtils;
import com.cnjson.common.utils.Encodes;
import com.cnjson.common.utils.IdGen;
import com.cnjson.common.utils.ImageUtils;
import com.cnjson.common.utils.StringUtils;
import com.cnjson.common.web.BaseController;
import com.google.common.collect.Lists;
import com.hongsuan.pplive.mobileAPI.utils.Convertor;
import com.hongsuan.pplive.mobileAPI.utils.JsonUtils;
import com.hongsuan.pplive.mobileAPI.utils.NetworkUtils;
import com.hongsuan.pplive.mobileAPI.utils.SignatureUtils;
import com.hongsuan.pplive.mobileAPI.utils.UploadFileUtils;
import com.hongsuan.pplive.mobileAPI.vo.LoginReturnStatus;
import com.hongsuan.pplive.mobileAPI.vo.ReturnList;
import com.hongsuan.pplive.mobileAPI.vo.ReturnObject;
import com.hongsuan.pplive.mobileAPI.vo.Status;
import com.hongsuan.pplive.mobileAPI.vo.UploadFile;
import com.hongsuan.pplive.modules.live.entity.LiveBacklist;
import com.hongsuan.pplive.modules.live.entity.LiveConcernFans;
import com.hongsuan.pplive.modules.live.entity.LiveGitConfig;
import com.hongsuan.pplive.modules.live.entity.LiveGoldContribution;
import com.hongsuan.pplive.modules.live.entity.LivePresentRecord;
import com.hongsuan.pplive.modules.live.entity.LiveRechargeRecord;
import com.hongsuan.pplive.modules.live.entity.LiveRoom;
import com.hongsuan.pplive.modules.live.service.LiveBacklistService;
import com.hongsuan.pplive.modules.live.service.LiveConcernFansService;
import com.hongsuan.pplive.modules.live.service.LiveGitConfigService;
import com.hongsuan.pplive.modules.live.service.LiveGoldContributionService;
import com.hongsuan.pplive.modules.live.service.LivePresentRecordService;
import com.hongsuan.pplive.modules.live.service.LiveRechargeRecordService;
import com.hongsuan.pplive.modules.live.service.LiveRoomService;
import com.hongsuan.pplive.modules.sys.entity.User;
import com.hongsuan.pplive.modules.sys.service.SystemService;
import com.hongsuan.pplive.modules.sys.utils.UserUtils;
import com.weixin.pay.entity.WeixinParameter;
import com.weixin.pay.utils.PayCommonUtil;

@Controller
@RequestMapping("/v2/user")
public class SysUserAPIController extends BaseController {

	public List<User> list = null;

	@Autowired
	private SystemService systemService;

	@Autowired
	private LiveBacklistService blacklistService;

	@Autowired
	private LiveConcernFansService concernFansService;

	@Autowired
	private LiveGitConfigService gitConfigService;

	@Autowired
	private LiveRechargeRecordService rechargeRecordService;

	@Autowired
	private LivePresentRecordService presentRecordService;

	@Autowired
	private LiveGoldContributionService liveGoldContributionService;

	@Autowired
	private LivePresentRecordService livePresentRecordService;

	@Autowired
	private LiveRechargeRecordService liveRechargeRecordService;

	@Autowired
	private LiveRoomService roomService;

	private static final String sdkAppId = Global.getAppId();
	private static final String expireTime = Global.getSigExpireTime();

	/**
	 * 用户登录
	 * 
	 * @param account
	 *            the user login name like: 19000000或者123@sian.com.
	 * @param oauthType
	 *            the type of oauthentication 0 保留, 1 QQ开放帐号, 2 微信开放帐号, 3
	 *            新浪微博开放帐号, 6 支付宝开放帐号, 7 豆瓣开放帐号, 8 人人网开放帐号 9 百度开放帐号, 10 搜狐开放帐号,
	 *            11 网易开放帐号, 12 开心网开放帐号, 13 MSN开放帐号, 14 Facebook开放帐号, 15
	 *            Google开放帐号, 16 Yahoo开放帐号, 17 腾讯微博开放帐号 QQ:0, weixin:1, weibo:2,
	 *            手机号:3.
	 * @param token
	 *            第三方登录的token,便于获取用户详细信息.不是必传的
	 * @return {code:0,"message":Global.SUCCESS,user}
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/appLogin")
	public @ResponseBody String appLogin(@RequestParam("account") String account,
			@RequestParam("oauthType") String oauthType, @RequestParam(value = "token", required = false) String token,
			HttpServletRequest request) {
		LoginReturnStatus status = new LoginReturnStatus();
		status.setCode(1);
		status.setMessage(Global.FAILED);

		// if (oauthType.equalsIgnoreCase("1")) {
		// OpenID openIDObj = new OpenID(token);
		// try {
		// String openID = openIDObj.getUserOpenID();
		//
		// com.qq.connect.api.weibo.UserInfo weiboUserInfo = new
		// com.qq.connect.api.weibo.UserInfo(token, openID);
		// com.qq.connect.javabeans.weibo.UserInfoBean weiboUserInfoBean =
		// weiboUserInfo.getUserInfo();
		// if (weiboUserInfoBean.getRet() == 0) {
		// // 获取用户的微博头像----------------------start
		// System.out.println("<image src=" +
		// weiboUserInfoBean.getAvatar().getAvatarURL30() + "/><br/>");
		// System.out.println("<image src=" +
		// weiboUserInfoBean.getAvatar().getAvatarURL50() + "/><br/>");
		// System.out.println("<image src=" +
		// weiboUserInfoBean.getAvatar().getAvatarURL100() + "/><br/>");
		// // 获取用户的微博头像 ---------------------end
		//
		// // 获取用户的生日信息 --------------------start
		// System.out.println("<p>尊敬的用户，你的生日是： " +
		// weiboUserInfoBean.getBirthday().getYear() + "年"
		// + weiboUserInfoBean.getBirthday().getMonth() + "月"
		// + weiboUserInfoBean.getBirthday().getDay() + "日");
		// // 获取用户的生日信息 --------------------end
		//
		// StringBuffer sb = new StringBuffer();
		// sb.append("<p>所在地:" + weiboUserInfoBean.getCountryCode() + "-" +
		// weiboUserInfoBean.getProvinceCode()
		// + "-" + weiboUserInfoBean.getCityCode() +
		// weiboUserInfoBean.getLocation());
		//
		// // 获取用户的公司信息---------------------------start
		// ArrayList<Company> companies = weiboUserInfoBean.getCompanies();
		// if (companies.size() > 0) {
		// // 有公司信息
		// for (int i = 0, j = companies.size(); i < j; i++) {
		// sb.append("<p>曾服役过的公司：公司ID-" + companies.get(i).getID() + " 名称-"
		// + companies.get(i).getCompanyName() + " 部门名称-"
		// + companies.get(i).getDepartmentName() + " 开始工作年-" +
		// companies.get(i).getBeginYear()
		// + " 结束工作年-" + companies.get(i).getEndYear());
		// }
		// } else {
		// // 没有公司信息
		// }
		// // 获取用户的公司信息---------------------------end
		//
		// }
		// } catch (QQConnectException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// }

		User user = new User();
		String id = "";
		try {
			if (!systemService.existed(account)) {
				String ip = NetworkUtils.getIpAddr(request);
				id = IdGen.generateId(10);
				while (systemService.existed("id", id)) {
					id = IdGen.generateId(10);
				}
				user.setNewRecord(true);
				user.setId(id);
				user.setLoginName(account);
				user.setName(account);
				user.setCreateDate(new Date());
				user.setAppFlag("1");
				user.setLoginFlag("1");
				user.setUserType("0");
				user.setAuthenStatus(0);
				user.setLevel(0);
				user.setAccount(0f);
				user.setLiveLevel(0);
				user.setEmpiricalValue(0l);
				user.setGold(0l);
				user.setMyIncome(0f);
				user.setMyConsumption(0f);
				user.setLoginIp(ip);
				if (StringUtils.isNotBlank(account)) {
					user.setPassword(SystemService.entryptPassword(account));
				}
				user.setRoleList(Lists.newArrayList());
			} else {
				user = UserUtils.getByAccount(account);
				id = user.getId();
				double days = 0;
				if (user.getCreateDate() != null) {
					days = DateUtils.getDistanceOfTwoDate(user.getCreateDate(), new Date());
				}
				if (days >= 360) {
					String sig = SignatureUtils.getSig(id, sdkAppId, expireTime);
					user.setSig(sig);
				}
			}
			user.setLoginDate(new Date());
			user.setOnlineState(1);
			if (StringUtils.isBlank(user.getSig())) {
				String sig = SignatureUtils.getSig(id, sdkAppId, expireTime);
				user.setSig(sig);
			}
			systemService.saveUser(user);
			com.hongsuan.pplive.mobileAPI.vo.UserVo vo = Convertor.userConvert2Vo(user);
			status.setMessage(Global.SUCCESS);
			status.setCode(0);
			status.setObject(vo);
		} catch (Exception e) {
			status.setMessage(Global.FAILED);
			status.setCode(10);
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return status.toString();
	}

	@RequestMapping(method = RequestMethod.GET, value = "/logout")
	public @ResponseBody String logout(@RequestParam("userId") String userId) {
		Status status = new Status();
		try {
			status.setCode(0);
			status.setMessage(Global.SUCCESS);
			UserUtils.logout(userId);
		} catch (Exception e) {
			logger.error(e.getMessage());
			status.setCode(10);
			status.setMessage(Global.FAILED);
		}
		return JsonUtils.toJson(status);
	}

	@RequestMapping(value = "/applyAnchorUpload", method = RequestMethod.POST)
	public @ResponseBody String applyAnchorUpload(@RequestParam("userId") String userId, HttpServletRequest request) {
		ReturnObject status = new ReturnObject();
		User user = systemService.getUser(userId);
		if (user == null) {
			status.setCode(1);
			status.setMessage("The user is not exist!");
			return JsonUtils.toJson(status);
		}
		try {
			UploadFileUtils.uploadMutrilFile(userId, request);
		} catch (Exception e) {
			status.setCode(2);
			status.setMessage("Upload file error!");
			logger.error(e.getMessage(), e);
			return JsonUtils.toJson(status);
		}
		return status.toString();
	}

	/**
	 * 向平台申请成为主播
	 * 
	 * @param userId
	 *            当用户ID
	 * @param name
	 *            用户真实姓名
	 * @param idCardNo
	 *            身份证号码
	 * @param phone
	 *            手机号码
	 * @param request
	 *            用户提交的图片流（如：手持人身份证图像）
	 * @return
	 */
	@RequestMapping(value = "/applyAnchor")
	public @ResponseBody String applyAnchor(@RequestParam("userId") String userId, @RequestParam("name") String name,
			@RequestParam("idCardNo") String idCardNo, @RequestParam("phone") String phone) {
		ReturnObject status = new ReturnObject();
		User user = systemService.getUser(userId);
		if (user == null) {
			status.setCode(1);
			status.setMessage("The user is not exist!");
			return JsonUtils.toJson(status);
		}
		/*
		 * try { UploadFileUtils.uploadMutrilFile(userId, request); } catch
		 * (Exception e) { status.setCode(2); status.setMessage(
		 * "Upload file error!"); logger.error(e.getMessage(), e); return
		 * JsonUtils.toJson(status); }
		 */
		user.setName(name);
		user.setPhone(phone);
		user.setMobile(phone);
		user.setNo(idCardNo);
		user.setAuthenStatus(1);// 申请成为主播.
		systemService.saveUser(user);
		return status.toString();
	}

	/**
	 * 用户登录
	 * 
	 * @param name
	 *            the user login name.
	 * @param password
	 *            the user login password.
	 * @return {code:0,"message":Global.SUCCESS,user}
	 *//*
		 * @RequestMapping(method = RequestMethod.GET, value = "/login")
		 * public @ResponseBody String login(@RequestParam("name") String
		 * name, @RequestParam("password") String password) { ReturnStatus
		 * status = new ReturnStatus(); status.setMessage(Global.FAILED); if
		 * (!systemService.existed(name)) { status.setCode(1);
		 * status.setMessage("user is not exist!"); return
		 * JsonUtils.toJson(status); } User user =
		 * systemService.getUserByLoginName(name); boolean equals =
		 * SystemService.validatePassword(password, user.getPassword()); if
		 * (equals) { status.setCode(0); status.setMessage(Global.SUCCESS);
		 * Map<String, User> data = new HashMap<String, User>();
		 * data.put("data", user); status.setData(data); } else {
		 * status.setCode(2); status.setMessage(Global.FAILED); }
		 * 
		 * return JsonUtils.toJson(status); }
		 */

	/**
	 * 增加/注册
	 * 
	 * @param data
	 *            当前用户ID
	 * @return success
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/add")
	public @ResponseBody String add(@RequestParam("user") String userJson) {
		Status ret = new Status();
		try {
			String receive = Encodes.urlDecode(Encodes.unescapeHtml(userJson));
			com.hongsuan.pplive.mobileAPI.vo.UserVo vo = JsonUtils.fromJson(receive,
					com.hongsuan.pplive.mobileAPI.vo.UserVo.class);
			User user = Convertor.voConvert2User(vo);
			// user.setPassword(SystemService.entryptPassword(vo.getPassword()));
			systemService.saveUser(user);
			ret.setCode(0);
			ret.setMessage(Global.SUCCESS);
		} catch (Exception e) {
			logger.error(e.getMessage());
			ret.setCode(10);
			ret.setMessage(Global.FAILED);
		}
		return JsonUtils.toJson(ret);
	}

	// /**
	// * 删除指定用户
	// *
	// * @param userId
	// * 当前用户ID
	// * @return success
	// */
	// @RequestMapping(method = RequestMethod.GET, value = "/delete")
	// public @ResponseBody String delete(@RequestParam("userId") String userId)
	// {
	// Status status = new Status();
	// try {
	// systemService.deleteUser(systemService.getUser(userId));
	// status.setCode(0);
	// status.setMessage(Global.SUCCESS);
	// } catch (Exception e) {
	// logger.error(e.getMessage());
	// status.setCode(10);
	// status.setMessage(Global.FAILED);
	// }
	// return JsonUtils.toJson(status);
	// }

	/**
	 * 更新用户信息
	 * 
	 * @param data
	 *            用户JSON结构
	 * @return success
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/update")
	public @ResponseBody String update(@RequestParam("user") String userJson, HttpServletRequest request) {
		ReturnObject status = new ReturnObject();
		try {
			String receive = Encodes.urlDecode(Encodes.unescapeHtml(userJson));
			com.hongsuan.pplive.mobileAPI.vo.UserVo vo = JsonUtils.fromJson(receive,
					com.hongsuan.pplive.mobileAPI.vo.UserVo.class);
			User user = Convertor.voConvert2User(vo);
			UploadFile upload = uploadPicture(user.getId(), request, status);
			if (upload != null) {
				user.setPhoto(upload.getRealPath());
			}

			systemService.saveUser(user);
			status.setCode(0);
			status.setMessage(Global.SUCCESS);
			status.setObject(vo);
		} catch (Exception e) {
			logger.error(e.getMessage());
			status.setCode(10);
			status.setMessage(Global.FAILED);
		}
		return JsonUtils.toJson(status);
	}

	@RequestMapping(value = "/uploadPhoto", method = RequestMethod.POST)
	public @ResponseBody String uploadPhoto(@RequestParam("userId") String userId, HttpServletRequest request) {
		ReturnObject ret = new ReturnObject();
		try {
			User user = systemService.getUser(userId);
			if (user == null) {
				ret.setCode(1);
				ret.setMessage("The user id is not exist!");
				return ret.toString();
			}
			UploadFile upload = uploadPicture(userId, request, ret);
			if (upload != null) {
				user.setPhoto(upload.getRealPath());
				ret.setObject(upload);
			}
			user.setUpdateBy(userId);
			user.setUpdateDate(new Date());
			systemService.updateUserInfo(user);
			ret.setCode(0);
			ret.setMessage(Global.SUCCESS);

		} catch (Exception e) {
			logger.error(e.getMessage());
			ret.setCode(10);
			ret.setMessage(Global.FAILED);
			e.printStackTrace();
		}
		System.out.println("return result=" + ret.toString());
		return ret.toString();
	}

	private UploadFile uploadPicture(String userId, HttpServletRequest request, ReturnObject ret) throws IOException {
		UploadFile upload = null;
		if (request != null && request instanceof MultipartHttpServletRequest) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			if (multipartRequest != null) {
				MultipartFile mf = multipartRequest.getFile("file");
				if (mf != null) {
					if (!UploadFileUtils.isPicture(mf.getOriginalFilename())) {
						ret.setCode(2);
						ret.setMessage("File format is not correct!");
						logger.error("File format is not correct!");
						throw new IOException(ret.getMessage());
					}
					if (!UploadFileUtils.validateSize(mf)) {
						ret.setCode(3);
						ret.setMessage("File size exceeds the allowable range!");
						logger.error("File size exceeds the allowable range!");
						throw new IOException(ret.getMessage());
					}
					upload = UploadFileUtils.dealFilePath(request, userId, mf.getOriginalFilename());
					String realPath = UploadFileUtils.getRequestRealPath(request, upload.getRelativePath());
					File file = new File(realPath);
					mf.transferTo(file);
					// general thumbnailImage
					new ImageUtils().thumbnailImage(realPath, 100, 150);
					int start = upload.getRelativePath().lastIndexOf(File.separator);
					int end = upload.getRelativePath().length();
					String thumbnail = ImageUtils.DEFAULT_PREVFIX + upload.getRelativePath().substring(start + 1, end);
					upload.setThumbnail(thumbnail);
					// update to db...
				}
			}
		}
		return upload;
	}

	/**
	 * 查询指定用户实例
	 * 
	 * @param userId
	 *            当前用户ID
	 * @return User 返回用户实例JSON数据格式
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/getUser")
	public @ResponseBody String getUser(@RequestParam("userId") String userId) {
		ReturnObject status = new ReturnObject();
		try {
			User user = systemService.getUser(userId);
			com.hongsuan.pplive.mobileAPI.vo.UserVo vo = Convertor.userConvert2Vo(user);
			// vo.setSig("");
			status.setCode(0);
			status.setMessage(Global.SUCCESS);
			status.setObject(vo);
		} catch (Exception e) {
			logger.error(e.getMessage());
			status.setCode(10);
			status.setMessage(Global.FAILED);
		}
		return status.toString();
	}

	/**
	 * 添加关注
	 * 
	 * @param selfUserId
	 *            当前用户即当前操作者
	 * @param userId
	 *            要关注的人Id.
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/addConcern")
	public @ResponseBody String addConcern(@RequestParam("selfUserId") String selfUserId,
			@RequestParam("userId") String userId) {
		Status status = new Status();
		try {
			if (selfUserId.equals(userId)) {
				status.setCode(1);
				status.setMessage("You can not concern youself!");
				return JsonUtils.toJson(status);
			}
			User user = systemService.getUser(selfUserId);
			LiveConcernFans fans = new LiveConcernFans();
			fans.setConcernUserId(userId);
			fans.setUser(user);
			fans.setCreateBy(userId);
			concernFansService.save(fans);
			status.setCode(0);
			status.setMessage(Global.SUCCESS);
		} catch (Exception e) {
			logger.error(e.getMessage());
			status.setCode(10);
			status.setMessage(Global.FAILED);
		}
		return JsonUtils.toJson(status);
	}

	/**
	 * 查询我的粉丝列表
	 * 
	 * @param userId
	 *            当前用户ID
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/queryFans")
	public @ResponseBody String queryFans(@RequestParam("userId") String userId) {
		ReturnList ret = new ReturnList();
		try {
			User user = systemService.getUser(userId);
			LiveConcernFans fans = new LiveConcernFans();
			// fans.setCurrentUser(user);
			fans.setCreateBy(userId);
			List<LiveConcernFans> fanLists = concernFansService.findList(fans);
			List<com.hongsuan.pplive.mobileAPI.vo.UserVo> users = new ArrayList<com.hongsuan.pplive.mobileAPI.vo.UserVo>();
			for (LiveConcernFans fan : fanLists) {
				com.hongsuan.pplive.mobileAPI.vo.UserVo vo = Convertor.userConvert2Vo(fan.getUser());
				// vo.setSig("");
				users.add(vo);
			}
			ret.setCode(0);
			ret.setMessage(Global.SUCCESS);
			ret.setList(fanLists);
		} catch (Exception e) {
			logger.error(e.getMessage());
			ret.setCode(10);
			ret.setMessage(Global.FAILED);
		}
		return ret.toString();
	}

	/**
	 * 拉黑操作
	 * 
	 * @param selfUserId
	 *            当前用户即当前操作者
	 * @param userId
	 *            被拉黑的人Id.
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/addBlacklist")
	public @ResponseBody String addBlacklist(@RequestParam("selfUserId") String selfUserId,
			@RequestParam("userId") String userId) {
		Status status = new Status();
		try {
			if (selfUserId.equals(userId)) {
				status.setCode(1);
				status.setMessage("You can not black youself!");
				return JsonUtils.toJson(status);
			}
			User owner = systemService.getUser(selfUserId);
			if (owner == null) {
				status.setCode(2);
				status.setMessage("The live room owner is not exist! ");
				return JsonUtils.toJson(status);
			}
			LiveRoom room = roomService.getByOwner(selfUserId);
			if (room == null || room.getUserId().equals(selfUserId)) {
				status.setCode(3);
				status.setMessage("You are no the live owner! ");
				return JsonUtils.toJson(status);
			}
			User user = systemService.getUser(userId);
			if (user == null) {
				status.setCode(4);
				status.setMessage("The user is not exist!");
				return JsonUtils.toJson(status);
			}
			LiveBacklist blackList = new LiveBacklist();
			blackList.setCreateBy(selfUserId);
			blackList.setUser(user);
			blacklistService.save(blackList);
			status.setCode(0);
			status.setMessage(Global.SUCCESS);
		} catch (Exception e) {
			logger.error(e.getMessage());
			status.setCode(10);
			status.setMessage(Global.FAILED);
		}
		return JsonUtils.toJson(status);
	}

	/**
	 * 查询黑名单列表
	 * 
	 * @author cgli
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/queryBlacklist")
	public @ResponseBody String queryBlacklist(@RequestParam("userId") String userId) {
		ReturnList ret = new ReturnList();
		try {
			User user = systemService.getUser(userId);
			LiveBacklist blackList = new LiveBacklist();
			blackList.setCreateBy(userId);
			List<LiveBacklist> lists = blacklistService.findList(blackList);
			List<com.hongsuan.pplive.mobileAPI.vo.UserVo> users = new ArrayList<com.hongsuan.pplive.mobileAPI.vo.UserVo>();
			for (LiveBacklist fan : lists) {
				com.hongsuan.pplive.mobileAPI.vo.UserVo vo = Convertor.userConvert2Vo(fan.getUser());
				// vo.setSig("");
				users.add(vo);
			}
			ret.setList(lists);
			ret.setCode(0);
			ret.setMessage(Global.SUCCESS);
		} catch (Exception e) {
			logger.error(e.getMessage());
			ret.setCode(10);
			ret.setMessage(Global.FAILED);
		}
		return ret.toString();
	}

	/**
	 * 查询我关注的主播列表
	 * 
	 * @param userId
	 *            当前用户ID
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/queryConcern")
	public @ResponseBody String queryConcern(@RequestParam("userId") String userId) {
		ReturnList ret = new ReturnList();
		try {
			LiveConcernFans fans = new LiveConcernFans();
			fans.setConcernUserId(userId);
			List<LiveConcernFans> fanLists = concernFansService.findList(fans);
			List<com.hongsuan.pplive.mobileAPI.vo.UserVo> users = new ArrayList<com.hongsuan.pplive.mobileAPI.vo.UserVo>();
			for (LiveConcernFans fan : fanLists) {
				com.hongsuan.pplive.mobileAPI.vo.UserVo vo = Convertor.userConvert2Vo(fan.getUser());
				// vo.setSig("");
				users.add(vo);
			}
			ret.setCode(0);
			ret.setList(users);
			ret.setMessage(Global.SUCCESS);
		} catch (Exception e) {
			logger.error(e.getMessage());
			ret.setCode(10);
			ret.setMessage(Global.FAILED);
		}
		return ret.toString();
	}

	/**
	 * 向主播发送礼物
	 * 
	 * @param senderId
	 *            发送者用户ID
	 * @param receiverId
	 *            接收者用户ID
	 * @return code:0 成功 1:余额不足，其他值: 失败
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/sendGift")
	public @ResponseBody String sendGift(@RequestParam("giftId") String giftId,
			@RequestParam("senderId") String senderId, @RequestParam("receiverId") String receiverId) {
		Status status = new Status();
		status.setCode(0);
		status.setMessage(Global.SUCCESS);
		if (senderId.equalsIgnoreCase(receiverId)) {
			status.setCode(3);
			status.setMessage("Can't send to yourself!");
			return JsonUtils.toJson(status);
		}
		User sender = systemService.getUser(senderId);
		if (sender == null) {
			status.setCode(1);
			status.setMessage("Sender user is not existed!");
			return JsonUtils.toJson(status);
		}
		User receiver = systemService.getUser(receiverId);
		if (receiver == null) {
			status.setCode(2);
			status.setMessage("receiver user is not existed!");
			return JsonUtils.toJson(status);
		}
		LiveGitConfig gift = gitConfigService.getByCode(giftId);
		if (gift == null) {
			status.setCode(4);
			status.setMessage("The gift code: " + giftId + " is not existed!");
			return JsonUtils.toJson(status);
		}
		long needDou = gift.getPrice();
		long hasDou = sender.getGold();
		if (hasDou <= 0 && sender.getAccount() <= 0) {
			status.setCode(6);
			status.setMessage("The sender account money is not enough!");
			return JsonUtils.toJson(status);
		}
		// 账号有钱自动转化金豆
		if (sender.getAccount() > 0 && hasDou <= 0) {
			hasDou = (long) (Global.moneyConvertor * sender.getAccount());
			sender.setAccount(0f);
		}
		if (hasDou <= 0 || needDou > hasDou) {
			status.setCode(5);
			status.setMessage("The sender JinDou is not enough!");
			return JsonUtils.toJson(status);
		}

		try {
			long cutDou = hasDou - needDou;
			long addDou = receiver.getGold() + needDou;
			sender.setGold(cutDou);
			sender.setMyConsumption((float) needDou);// 消费记录
			sender.setEmpiricalValue(gift.getExp() + sender.getEmpiricalValue());
			systemService.updateUserAccount(sender);
			LiveGoldContribution contibution = new LiveGoldContribution();
			contibution.setCount(needDou);
			contibution.setCreateById(senderId);
			contibution.setCreateBy(senderId);
			// contibution.setUser(receiver);
			contibution.setUserId(receiverId);
			contibution.setCreateDate(new Date());
			contibution.setUpdateDate(new Date());
			contibution.setDelFlag("0");
			liveGoldContributionService.save(contibution);

			receiver.setMyIncome(receiver.getMyIncome() + needDou);
			receiver.setGold(addDou);
			systemService.updateUserAccount(receiver);

		} catch (Exception e) {
			logger.error(e.getMessage());
			status.setCode(10);
			status.setMessage(Global.FAILED);
		}
		return JsonUtils.toJson(status);
	}

	/**
	 * 用户申请充值操作
	 * 
	 * @param userId
	 *            用户ID
	 * @param money
	 *            充值金额（单位：元）
	 * @param type
	 *            1：微信支付,2:支付宝支付，3：网银支付
	 * @return code 0 成功，其他值失败。
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/addRecharge")
	public @ResponseBody String addRecharge(@RequestParam("userId") String userId, @RequestParam("money") Float money,
			@RequestParam("type") Integer type, @RequestParam("tradeNo") String tradeNo, HttpServletRequest request) {
		Status status = new Status();
		User user = systemService.getUser(userId);
		if (user == null) {
			status.setCode(1);
			status.setMessage("Sender user is not existed!");
			return JsonUtils.toJson(status);
		}
		if (money <= 0) {
			status.setCode(2);
			status.setMessage("The recharge money should not be less then 0!");
			return JsonUtils.toJson(status);
		}
		// TODO 订单号必须要为唯一
		String retObject = "";
		try {
			// 如果是微信支付
			if (type == 1) {
				WeixinParameter info = new WeixinParameter();
				info.setFee((long) (money * 100));// convert to fen
				info.setIp(NetworkUtils.getIpAddr(request));
				info.setTradeNo(tradeNo);
				info.setComment("微信充值支付");
				info.setTradeType("APP");
				retObject = PayCommonUtil.perPay(info);
			}

			LiveRechargeRecord recharge = new LiveRechargeRecord();
			recharge.setNewRecord(true);
			recharge.setId(tradeNo);
			recharge.setAmount(user.getAccount());
			recharge.setType(type);
			recharge.setRemarks(tradeNo);
			// recharge.setCreateBy(user);
			recharge.setCreateById(userId);
			recharge.setState(1);
			recharge.setCreateDate(new Date());
			liveRechargeRecordService.save(recharge);

			// user.setAccount(user.getAccount() + money);
			// systemService.updateUserAccount(user);
		} catch (Exception e) {
			logger.error(e.getMessage());
			status.setCode(10);
			status.setMessage(Global.FAILED);
		}
		return JsonUtils.toJson(status);
	}

	/**
	 * 提现操作
	 * 
	 * @param userId
	 *            用户ID
	 * @param money
	 *            提现金额
	 * @param type
	 *            1：微信支付,2:支付宝支付，3：网银支付
	 * @return code 0 成功，其他值失败。
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/applyPresent")
	public @ResponseBody String applyPresent(@RequestParam("userId") String userId,
			@RequestParam("account") String account, @RequestParam("money") Float money,
			@RequestParam("type") Integer type, HttpServletRequest request) {
		Status status = new Status();
		User user = systemService.getUser(userId);
		if (user == null) {
			status.setCode(1);
			status.setMessage("Sender user is not existed!");
			return JsonUtils.toJson(status);
		}
		if (money > user.getAccount()) {
			status.setCode(2);
			status.setMessage("Your account money is not enough!");
			return JsonUtils.toJson(status);
		}
		if (user.getAuthenStatus() != 2) {
			status.setCode(3);
			status.setMessage("User is not authentication yet,please authenticate first!");
			return JsonUtils.toJson(status);
		}
		try {
			String pdate = DateUtils.formatDate(new Date(), "yyyyMMdd");
			// 批次号 必填，格式：当天日期[8位]+序列号[3至16位]，如：201008010000001
			String lineNo = pdate + IdGen.generateId(10);
			LivePresentRecord present = new LivePresentRecord();
			present.setLineNo(lineNo);
			present.setAccount(account);
			present.setAmount(money);
			present.setCreateById(userId);
			present.setCreateDate(new Date());
			present.setNewRecord(true);
			present.setState(1);
			present.setType(type);
			livePresentRecordService.save(present);
			status.setCode(0);
			// 提现要打折算
			status.setMessage(Global.SUCCESS + ",you present apply is submit,please wait for audit!");
		} catch (Exception e) {
			logger.error(e.getMessage());
			status.setCode(10);
			status.setMessage(Global.FAILED);
		}
		return JsonUtils.toJson(status);
	}

	/**
	 * 查询充值记录
	 * 
	 * @param userId
	 *            用户ID
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/queryRecharge")
	public @ResponseBody String queryRecharge(@RequestParam("userId") String userId) {
		ReturnList ret = new ReturnList();
		try {
			LiveRechargeRecord liveRechargeRecord = new LiveRechargeRecord();
			User user = systemService.getUser(userId);
			liveRechargeRecord.setCreateBy(userId);
			List<LiveRechargeRecord> lists = rechargeRecordService.findList(liveRechargeRecord);
			ret.setCode(0);
			ret.setList(lists);
			ret.setMessage(Global.SUCCESS);
		} catch (Exception e) {
			logger.error(e.getMessage());
			ret.setCode(10);
			ret.setMessage(Global.FAILED);
		}
		return ret.toString();
	}

	/**
	 * 查询提现记录
	 * 
	 * @param userId
	 *            用户ID
	 * @return json数组记录列表
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/queryPresent")
	public @ResponseBody String queryPresent(@RequestParam("userId") String userId) {
		ReturnList ret = new ReturnList();
		try {
			LivePresentRecord livePresentRecord = new LivePresentRecord();
			User user = systemService.getUser(userId);
			livePresentRecord.setCreateBy(userId);
			List<LivePresentRecord> lists = presentRecordService.findList(livePresentRecord);
			ret.setCode(0);
			ret.setMessage(Global.SUCCESS);
			ret.setList(lists);
		} catch (Exception e) {
			logger.error(e.getMessage());
			ret.setCode(10);
			ret.setMessage(Global.FAILED);
		}
		return ret.toString();
	}

	@RequestMapping(method = RequestMethod.GET, value = "/moneyToGold")
	public @ResponseBody String moneyToGold(@RequestParam("userId") String userId) {
		Status status = new Status();
		User user = systemService.getUser(userId);
		if (user == null) {
			status.setCode(1);
			status.setMessage("The user is not existed!");
			return JsonUtils.toJson(status);
		}
		if (user.getAccount() <= 0) {
			status.setCode(2);
			status.setMessage("The user account is not money!");
			return JsonUtils.toJson(status);
		}
		try {
			long dou = (long) (user.getAccount() * Global.moneyConvertor + user.getGold());
			user.setAccount(0f);
			user.setGold(dou);
			systemService.updateUserAccount(user);
		} catch (Exception e) {
			logger.error(e.getMessage());
			status.setCode(10);
			status.setMessage(Global.FAILED);
		}
		return JsonUtils.toJson(status);
	}

	@RequestMapping(method = RequestMethod.GET, value = "/goldToMoney")
	public @ResponseBody String goldToMoney(@RequestParam("userId") String userId) {
		Status status = new Status();
		User user = systemService.getUser(userId);
		if (user == null) {
			status.setCode(1);
			status.setMessage("The user is not existed!");
			return JsonUtils.toJson(status);
		}
		if (user.getGold() < Global.moneyConvertor) {
			status.setCode(2);
			status.setMessage("The user gold is less then " + Global.moneyConvertor + " not enough!");
			return JsonUtils.toJson(status);
		}
		try {
			int money = (int) (user.getGold() / Global.moneyConvertor);
			user.setAccount(user.getAccount() + money);
			user.setGold(0l);
			systemService.updateUserAccount(user);
		} catch (Exception e) {
			logger.error(e.getMessage());
			status.setCode(10);
			status.setMessage(Global.FAILED);
		}
		return JsonUtils.toJson(status);
	}
}